package cn.hchaojie.blog.service;

import java.io.IOException;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.hchaojie.blog.domain.Category;
import cn.hchaojie.blog.mapper.CategoryMapper;

/**
 * service职责：开始事务，提交事务，调用mapper做数据库查询
 * 处理业务逻辑，
 * @author hchaojie
 *
 */
public class CategoryService {
	CategoryMapper mapper;

	public List<Category> findAll() {
		SqlSession session = null;
		try {
			SqlSessionFactory factory = new SqlSessionFactoryBuilder()
					.build(Resources.getResourceAsStream("mybatis.xml"));
			
			session = factory.openSession();
			mapper = session.getMapper(CategoryMapper.class);
			List<Category> data = mapper.findAll();
			
			return data;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.close();
			}
		}
		
		return null;
	}
	
	public void insert(Category category) {
		SqlSession session = null;
		try {
			SqlSessionFactory factory = new SqlSessionFactoryBuilder()
					.build(Resources.getResourceAsStream("mybatis.xml"));
			
			session = factory.openSession();
			mapper = session.getMapper(CategoryMapper.class);
			
			mapper.insert(category);
			session.commit();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
}
